package com.lxyblog2030.blog.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lxyblog2030.blog.pojo.Comment;
import com.lxyblog2030.blog.pojo.Tag;
import com.lxyblog2030.blog.pojo.Type;
import com.lxyblog2030.blog.queryvo.DetailedBlog;
import com.lxyblog2030.blog.queryvo.FirstPageBlog;
import com.lxyblog2030.blog.queryvo.RecommendBlog;
import com.lxyblog2030.blog.service.BlogService;
import com.lxyblog2030.blog.service.CommentService;
import com.lxyblog2030.blog.service.TagService;
import com.lxyblog2030.blog.service.TypeService;
import com.lxyblog2030.blog.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class IndexController {
    @Autowired
    private BlogService blogService;

    @Autowired
    private TagService tagService;

    @Autowired
    private TypeService typeService;


    @Autowired
    private CommentService commentService;



    @GetMapping("/")
    public String index(Model model, @RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
        PageHelper.startPage(pageNum,6);
        List<FirstPageBlog> firstPageBlog = blogService.getAllFirstPageBlog();
        List<Type> allType = typeService.getAllType();
        List<Tag> allTag = tagService.getAllTag();
        List<RecommendBlog> recommendedBlog = blogService.getRecommendedBlog();
        PageInfo<FirstPageBlog> pageInfo = new PageInfo<>(firstPageBlog);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("tags",allTag);
        model.addAttribute("types",allType);
        model.addAttribute("recommenedBlogs",recommendedBlog);
        return "index";
    }
    @GetMapping(value = "/search")
    public String search(Model model,@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum,@RequestParam String query){

        PageHelper.startPage(pageNum,100);
        List<FirstPageBlog> searchBlog = blogService.getSearchBlog(query);
        PageInfo<FirstPageBlog> pageInfo = new PageInfo<>(searchBlog);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("query",query);
        return "search";


    }


    @GetMapping(value = "/blog/{id}")
    public String blog(@PathVariable long id, Model model){
        DetailedBlog detailedBlog = blogService.getDetailedBlog(id);
        List<Comment> comments = commentService.listCommentByBlogId(id);
        model.addAttribute("comments",comments);
        model.addAttribute("blog",detailedBlog);
        return "blog";
    }

    @GetMapping("/about")
    public String about() {
        return "about";
    }

}
